package q1694_reformatNumber;

public class Solution {
    /*
    重新格式化电话号码
    直接分情况讨论即可
     */
    public String reformatNumber(String number) {
        StringBuilder sb = new StringBuilder();
        StringBuilder ans = new StringBuilder();
        for (int i = 0; i < number.length(); ++i) {
            if (Character.isDigit(number.charAt(i))) sb.append(number.charAt(i));
        }
        int left = sb.length() % 3, group = sb.length() / 3;
        if (group < 1) {
            return sb.toString();
        } else {
            if (left == 1) {
                for (int i = 0; i < group - 1; ++i) {
                    ans.append(sb.substring(i * 3, (i + 1) * 3)).append("-");
                }
                ans.append(sb.substring((group - 1) * 3, (group - 1) * 3 + 2)).append("-").append(sb.substring((group - 1) * 3 + 2, sb.length()));

            } else if (left == 2) {
                for (int i = 0; i < group; ++i) {
                    ans.append(sb.substring(i * 3, (i + 1) * 3)).append("-");
                }
                ans.append(sb.substring(sb.length() - 2, sb.length()));
            } else {
                for (int i = 0; i < group - 1; ++i) {
                    ans.append(sb.substring(i * 3, (i + 1) * 3)).append("-");
                }
                ans.append(sb.substring((group - 1) * 3, group * 3));
            }
        }
        return ans.toString();
    }
}
